#!/bin/sh

# Exit if any subcommand or pipeline returns a non-zero status.
set -e

BINARYPATH=/usr/bin
SBINARYPATH=/usr/sbin
SOCKETPATH=/var/run
DAEMON_ARGS=""

[ -f "$SBINARYPATH/pdns_recursor" ] || exit 0

[ -r /etc/default/pdns ] && . /etc/default/pdns

[ "$START" = "no" ] && exit 0

# Make sure that /var/run exists
mkdir -p $SOCKETPATH
cd $SOCKETPATH

pdns_recursor="$SBINARYPATH/pdns_recursor $DAEMON_ARGS $EXTRAOPTS"

doPC()
{
	ret=$($BINARYPATH/rec_control $EXTRAOPTS $1 $2 2> /dev/null)
}

NOTRUNNING=0
doPC ping || NOTRUNNING=$?

case "$1" in
	status)
		if test "$NOTRUNNING" = "0" 
		then 
			echo "running"
		else
			echo "not running"
			exit 3
		fi 
	;;	

	stop)
		echo -n "Stopping PowerDNS recursing nameserver: "
		if test "$NOTRUNNING" = "0" 
		then 
			doPC quit
			echo $ret
		else
			echo "not running"
		fi 
	;;		

	force-stop)
		echo -n "Stopping PowerDNS recursing nameserver: "
		killall -v -9 pdns_recursor
		echo "killed"
	;;

	start)
		echo -n "Starting PowerDNS recursing nameserver: "
		if test "$NOTRUNNING" = "0" 
		then 
			echo "already running"
		else
			if $pdns_recursor --daemon 
			then
				echo "started"	
         	else
				echo "starting failed"
          exit 1
			fi
		fi 
	;;		

	force-reload | restart)
		echo -n "Restarting PowerDNS recursing nameserver: "
		if test "$NOTRUNNING" = "1" 
		then 
			echo "not running, starting"
		else
			
			echo -n stopping and waiting.. 
			doPC quit
			sleep 3
			echo done
		fi
		$0 start
	;;

	reload) 
		echo -n "Reloading PowerDNS recursing nameserver: "
		if test "$NOTRUNNING" = "0" 
		then 
			doPC reload-zones
			echo requested reload
		else
			echo not running yet
			$0 start
		fi 
	;;		
		
	monitor)
		if test "$NOTRUNNING" = "0" 
		then 
			echo "already running"
		else
			$pdns_recursor --daemon=no --log-common-errors --trace
		fi 
	;;		

	dump)
		if test "$NOTRUNNING" = "0" 
		then 
			doPC get-all
			echo $ret
		else
			echo "not running"
		fi 
	;;		


	*)
	echo pdns [start\|stop\|force-reload\|reload\|restart\|status\|monitor\|dump]

	;;
esac


